<template>
<div class="vue-box">
  <div class="c-panel">
    <!-- 参数栏 -->
    <div class="c-title">检索参数</div>
    <el-form @submit.native.prevent class="conditional_filter">
      <sa-item v-model="p.search" type="text" name="模糊搜索" />
      <sa-item v-model="p.type" type="text" name="请求方式" />
      <sa-item type="date-range" name="请求日期" :start.sync="p.startTime" :end.sync="p.endTime" :clearable="true" />
      <div class="c-item">
        <el-button type="primary" icon="el-icon-search" @click="p.current = 1; f5()">查询</el-button>
      </div>
    </el-form>
    <!-- ------------- 快捷按钮 ------------- -->
    <div class="fast-btn" style="margin-top: -10px;">
      <el-button plain type="danger" icon="el-icon-delete" @click="deleteByIds()">删除</el-button>
      <el-button plain type="warning" icon="el-icon-download" @click="sa.exportExcel()">导出</el-button>
      <el-button plain icon="el-icon-refresh" @click="sa.tagsView.f5CurrView()">重置</el-button>
      <el-button plain type="success" icon="el-icon-view" @click="f5StaData()">统计</el-button>
    </div>
    <!-- ------------- 数据列表 ------------- -->
    <el-table ref="data-table" class="data-table" :data="dataList" size="small" stripe border>
      <<sa-td type="selection" />
      <sa-td type="index" name="序号" width="80px" />
      <sa-td type="text" name="接口描述" prop="name" width="200px"/>
      <sa-td type="text" name="IP"  prop="ip" width="180px"/>
      <sa-td type="text" name="请求方式" prop="type" width="100px"/>
      <sa-td type="text" name="接口地址" prop="api"  width="220px"/>
      <sa-td type="text" name="响应码" width="100px">
        <template slot-scope="s">
          <p style="padding-left: 3px;" @click="seeResString(s.row)">
            <b v-if="s.row.resCode == 200" style="color: green;">{{ s.row.resCode }}</b>
            <b v-else style="color: red;">{{ s.row.resCode }}</b>
          </p>
        </template>
      </sa-td>
      <sa-td type="text" name="时间">
        <template slot-scope="s">
          <span>
            {{ sa.forDate(s.row.startTime, 'yyyy-MM-dd HH:mm:ss') }} ~ {{ sa.forDate(s.row.endTime, 'yyyy-MM-dd HH:mm:ss') }}  
            <b style="color: green;padding-left: 10px;">耗时：{{ (s.row.costTime + 0.0) / 1000 }}s</b>
          </span>
        </template>
      </sa-td>
      <sa-td name="操作" fixed="right" width="120px">
        <template slot-scope="s">
          <el-button type="text" @click="copy(s.row)">复制</el-button>
          <el-button type="text" @click="del(s.row)">删除</el-button>
        </template>
      </sa-td>
    </el-table>
    <!-- 分页 -->
    <div v-if="dataCount">
      <sa-item type="page" :curr.sync="p.current" :size.sync="p.size" :total="dataCount" @change="f5()" />
    </div>
  </div>
</div>
</template>

<script>
export default {
  name: 'api-log-list',
  data() {
    return {
      p: { // 查询参数
        current: 1,
        size: 10,
        search: null,
        type: null,
        userId: null,
        startTime: null,
        endTime: null,
        sortField: 'id desc'
      },
      dataCount: null,
      // 数据集合
      dataList: [],
      // 字典
      dims: [],
      // 当前是否为最新统计数据
      isNewestSta: false,
      staData: {
        // 总计耗时
        cost_time_count: 0,
      },
    }
  },
  created: function () {
    let gd = sa.$sys.getCurd()
    if (gd) {
      this.dims = gd
    } else {
      sa.error('未获取到字典信息！');
    }
    this.f5();
    // 监听表单动作
    sa.onInputEnter();
  },
  methods: {
    // 刷新
    f5: function () {
      sa.ajax('/api/log/getList', sa.removeNull(this.p), function (res) {
        // 数据
        this.dataList = res.data;
        // 数据总数
        this.dataCount = res.dataCount;
        // 刷新表格高度
        sa.f5TableHeight();
        this.isNewestSta = false;
      }.bind(this));
    },
    // 统计数据
    f5StaData: function () {
      var fn = function () {
        var str = '<b>总计请求：' + this.dataCount + ' 次</b><br/>' +
          '<b>总计耗时：' + this.getDuration(this.staData.cost_time_count) + ' </b>';
        str = '<big>' + str + '</big>'
        sa.layer.alert(str, {
          title: '统计数据'
        });
      }.bind(this);
      if (this.isNewestSta) {
        fn()
      } else {
        sa.ajax('/api/log/staBy', sa.removeNull(this.p), function (res) {
          this.staData.cost_time_count = res.data;
          this.isNewestSta = true;
          fn();
        }.bind(this));
      }
    },
    // 复制
    copy: function (data) {
      sa.copyText(JSON.stringify(data));
      sa.ok2('已成功复制到剪贴板');
    },
    // 查看：访问参数
    seeReqParam: function (data) {
      if (data.param) {
        var jsonStr = data.param;
        jsonStr = JSON.stringify(JSON.parse(jsonStr), null, '\t');
        layer.prompt({
          title: '请求参数',
          // 点击遮罩关闭
          shadeClose: true,
          // 多行输入
          formType: 2,
          // 要显示的字符串
          value: jsonStr,
          // 最大输入字符长度
          maxlength: 9999999999,
          // 弹窗尺寸
          area: ['600px', '400px'],
          yes: function (index, layero) {
            // 如果设定了yes回调，需进行手工关闭
            layer.close(index);
          }
        })
      }
    },
    // 查看：返回参数
    seeResString: function (data) {
      var jsonStr = data.resStr;
      jsonStr = JSON.stringify(JSON.parse(jsonStr), null, '\t');
      layer.prompt({
        title: '返回参数',
        shadeClose: true, // 点击遮罩关闭
        formType: 2, // 多行输入
        value: jsonStr, // 要显示的字符串
        maxlength: 9999999999, // 最大输入字符长度
        area: ['600px', '400px'], // 弹窗尺寸
        yes: function (index, layero) {
          layer.close(index); // 如果设定了yes回调，需进行手工关闭
        }
      })
    },
    // 删除
    del: function (data) {
      alert(data.id)
      sa.confirm('是否删除，此操作不可撤销', function () {
        sa.ajax('/api/log/delete', {
          id: data.id
        }, function (res) {
          sa.ok('删除成功');
          this.f5();
        }.bind(this), {
          type: "get"
        })
      }.bind(this));
    },
    // 批量删除
    deleteByIds: function () {
      // 获取选中元素的id列表
      let selection = this.$refs['data-table'].selection;
      let ids = sa.getArrayField(selection, 'id');
      if (selection.length == 0) {
        return sa.msg('请至少选择一条数据')
      }
      // 提交删除
      sa.confirm('是否批量删除选中数据？此操作不可撤销', function () {
        sa.ajax('/api/log/deleteByIds', {
          ids: ids
        }, function (res) {
          sa.ok('删除成功');
          this.f5();
        }.bind(this), {
          type: 'post'
        })
      }.bind(this));
    },
    // 计算耗时
    getDuration: function (my_time) {
      var days = my_time / 1000 / 60 / 60 / 24;
      var daysRound = Math.floor(days);
      var hours = my_time / 1000 / 60 / 60 - (24 * daysRound);
      var hoursRound = Math.floor(hours);
      var minutes = my_time / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
      var minutesRound = Math.floor(minutes);
      var seconds = my_time / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
      seconds = parseInt(seconds);
      if (daysRound >= 1) {
        return daysRound + '天' + hoursRound + '小时';
      } else if (hoursRound >= 1) {
        return hoursRound + '小时' + hoursRound + '分';
      } else if (minutesRound >= 1) {
        return minutesRound + '分' + seconds + '秒';
      } else {
        return seconds + '秒';
      }
    }
  }
}
</script>

<style scoped>
.type-box b {
  padding: 3px 7px;
  border-radius: 3px;
  font-size: 12px;
}

/* .api span{background-color: ; color: #409EFF; border: 1px #409EFF solid; border-radius: 2px; padding: 3px 5px;} */
.api {
  color: #44f;
  font-weight: 700;
  margin-left: 3px;

}

.p {
  display: inline-block;
  line-height: 1.4;
  padding: 2px 4px;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fff2f4;
  color: #c7254e;
}

.ip {
  background-color: ;
  color: #409EFF;
  border: 1px #409EFF solid;
  border-radius: 2px;
  padding: 3px 5px;
}

.string {
  line-height: 1.4;
  padding: 2px 4px;
  border-radius: 4px;
  cursor: pointer;
}
</style>
